import java.util.ArrayList;
import java.util.HashSet;

public class TerminalSynchronization extends Node {
	private ArrayList<Integer> states;
	private String input;
	private String result;

	public TerminalSynchronization(ArrayList<Integer> states, String input)
	{
		this.states = states;
		this.input = input;
	}

	@Override
	public Node ApplyZero()
	{
		return apply(0);
	}

	@Override
	public Node ApplyOne()
	{
		return apply(1);
	}

	@Override
	public boolean isTerminated()
	{
		boolean stop = states.size() == 1;
		if (stop)
		{
			result = input;
		}
		return stop;
	}

	@Override
	public boolean isEqual(Node e)
	{
		TerminalSynchronization t = (TerminalSynchronization) e;
		if(t.states .size() != states.size())
			return false;
		return t.states.containsAll(states);
	}

	private TerminalSynchronization apply(int in)
	{
		HashSet<Integer> hash = new HashSet<Integer>(states.size());
		ArrayList<Integer> nextStates = new ArrayList<Integer>();
		for (Integer current : states)
		{
			Integer next = nextState[current][in];
			if (!hash.contains(next)){
				nextStates.add(next);
				hash.add(next);
			}
		}
		return new TerminalSynchronization(nextStates, input + in);
	}

	@Override
	public String getResult()
	{
		return result;
	}

	@Override
	public String[][] getTable()
	{
		int n = nextState.length;
		String[][] a = new String[n][2];
		for (int i = 0; i < n; i++)
		{
			a[i][0] = "" + i;
			a[i][1] = "" + states.get(0);
		}
		return a;
	}
	@Override
	public String toString()
	{
		return states.toString();
	}
}
